package controller

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"net/http"
	urlEncode "net/url"
	"product-service/common"
)

var bucket *oss.Bucket

func init() {
	client, err := oss.New("oss-cn-beijing.aliyuncs.com",
		"LTAI5t6uN12xCk3ozTEu4oMD",
		"MFVlyDu8NZEnW6G8HkcZIAEgvi778U")
	if err != nil {
		fmt.Println(("阿里云权限失败"))
	}
	bucket, err = client.Bucket("huangtiandi")
	if err != nil {
		fmt.Println("bucket获取失败")
	}
}

type SignatureController struct {
}

func (t *SignatureController) RegisterRouter(engine *gin.Engine) {
	group := engine.Group("/signature")
	group.POST("/putObject", t.PutObject)
	//group.GET("/getObject",t.GetObject)
}

func (t *SignatureController) PutObject(context *gin.Context) {
	if bucket == nil {
		context.JSON(http.StatusInternalServerError, common.Error.WithMsg("bucket获取失败"))
		return
	}

	filename := context.PostForm("filename")

	url, err := bucket.SignURL(filename, oss.HTTPPut, 10, oss.ContentType("image/jpg"))
	if err != nil {
		context.JSON(http.StatusInternalServerError, common.Error.WithMsg("上传签名获取失败"))
	}
	//url 解码
	url, err = urlEncode.QueryUnescape(url)
	context.JSON(http.StatusOK, common.OK.WithData(url))
}

func (t *SignatureController) GetObject(context *gin.Context) {
	if bucket == nil {
		context.JSON(http.StatusInternalServerError, common.Error.WithMsg("bucket获取失败"))
		return
	}
	filename := context.PostForm("filename")
	url, err := bucket.SignURL(filename, oss.HTTPGet, 60*60, oss.ContentType("image/jpg"))
	if err != nil {
		context.JSON(http.StatusInternalServerError, common.Error.WithMsg("get签名获取失败"))
	}
	//url 解码
	url, err = urlEncode.QueryUnescape(url)
	context.JSON(http.StatusOK, common.OK.WithData(url))
}
